mod client_data_table;
mod home;
mod login;
pub(crate) mod process_list;
mod processing;
pub(crate) mod server_data_table;
pub(crate) mod server_error;
pub(crate) mod loading;
pub(crate) mod stats;
mod crud;
mod table_edit;
mod test2;
mod test3;
mod test4;
mod test6;
mod test7;
pub(crate) mod upload_file;

pub use self::login::*;
pub use self::processing::*;
use gloo_net::http::Request;
pub use home::*;
pub use crud::*;
use leptos::prelude::document;
use wasm_bindgen::{JsCast, JsValue};
use web_sys::js_sys::Uint8Array;
use web_sys::BlobPropertyBag;
pub async fn export_xlsx_with_dao(
    name: &str,
    dao_name: &str,
    header_cells: String,
    filters: Option<String>,
    orders: Option<String>,
) -> Result<(), String> {
    let datas = (dao_name, header_cells, filters, orders);
    let response = Request::post("/export_xlsx_with_dao")
        .json(&datas)
        .or_else(|e| Err(e.to_string()))?
        .send()
        .await
        .or_else(|e| Err(e.to_string()))?;
    let bytes = response.binary().await.or_else(|e| Err(e.to_string()))?;
    download_xlsx_file(name, bytes).map_err(|e| e.to_string())?;
    Ok(())
}
pub fn download_xlsx_file_with_url(
    name: &str,
    extension: &str,
    url: &str,
    params: Option<String>,
) -> Result<(), String> {
    let to_err = |err: JsValue| err.as_string().unwrap_or("js_error".to_string());
    let a = web_sys::Document::create_element(&document(), "a")
        .or_else(|err| Err(to_err(err)))?
        .dyn_into::<web_sys::HtmlAnchorElement>()
        .or_else(|_err| Err("Element转换出错".to_string()))?;
    let mut url = url.to_string();
    if let Some(params) = params {
        url.push_str("?");
        url.push_str(&params);
    }
    a.set_href(&url);
    if !name.is_empty() {
        let file_name=format!("{}.{}", name, extension);
        a.set_download(&file_name);
    }else{
        a.set_download("");
    }
    a.click();
    web_sys::Url::revoke_object_url(&url).unwrap();
    Ok(())
}
pub fn download_xlsx_file(name: &str, content: Vec<u8>) -> Result<(), String> {
    let to_err = |err: JsValue| err.as_string().unwrap_or("js_error".to_string());
    let uint8_array = Uint8Array::new_with_length(content.len() as u32);
    uint8_array.copy_from(&content);
    // let blob_parts = content
    //     .iter()
    //     .map(|&byte| JsValue::from(byte))
    //     .collect::<web_sys::js_sys::Array>();
    let blob_options = BlobPropertyBag::new();
    blob_options.set_type("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    let blob =
        web_sys::Blob::new_with_u8_array_sequence_and_options(&uint8_array, &blob_options).unwrap();
    let url = web_sys::Url::create_object_url_with_blob(&blob).unwrap();
    let a = web_sys::Document::create_element(&document(), "a")
        .or_else(|err| Err(to_err(err)))?
        .dyn_into::<web_sys::HtmlAnchorElement>()
        .or_else(|_err| Err("Element转换出错".to_string()))?;
    a.set_href(&url);
    let file_name = format!("{}.xlsx", name);
    a.set_download(&file_name);
    a.click();
    web_sys::Url::revoke_object_url(&url).unwrap();
    Ok(())
}

// #[cfg(feature = "ssr")]
// pub async fn export_xlsx_with_dao(
//     dao_name: String,
//     header_cells: String,
//     filters: Option<String>,
//     orders: Option<String>,
// ) -> impl axum::response::IntoResponse {
//     use axum::{
//         body::Body,
//         extract::Path,
//         http::{header, HeaderMap, StatusCode},
//         response::{IntoResponse, Response},
//     };
//     use futures_util::stream;
//     use shq_common::prelude::OrderItems;
//     use shq_common::prelude::WhereCauses;
//     let hcs = serde_json::from_str(&header_cells).unwrap();
//     let fs: Option<WhereCauses> = filters.map(|f| serde_json::from_str(&f).unwrap());
//     let os: Option<OrderItems> = orders.map(|o| serde_json::from_str(&o).unwrap());
//     let res = shq_common::prelude::export_xlsx_with_dao(dao_name.as_str(), hcs, fs, os).await;
//     match res {
//         Ok(data) => {
//             let chunks: Vec<std::io::Result<_>> = vec![Ok(data)];
//             let s = stream::iter(chunks);
//             let body = Body::from_stream(s);
//             let mut headers = HeaderMap::new();
//             headers.insert(
//                 header::CONTENT_TYPE,
//                 "application/vnd.ms-excel".parse().unwrap(),
//             );
//             Ok((headers, body))
//         }
//         Err(err) => Err((StatusCode::BAD_REQUEST, err.to_string())),
//     }
// }
